﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace WinFormClientApp
{
    public partial class ClientApp : Form
    {
        // remote object reference
        private RemotingObjects.IRemoteObject remoteObject;
        private int instanceNumber = 0;
        private String lastID = "";
        private String currentID = "";
        public ClientApp()
        {
            try //channel establishment and remote object connection
            {
                TcpChannel channel = new TcpChannel();
                ChannelServices.RegisterChannel(channel, true);
                remoteObject = (RemotingObjects.IRemoteObject)Activator.GetObject(typeof(RemotingObjects.IRemoteObject), "tcp://localhost:12000/HostObject");

            }
            catch (Exception e)
            {
                MessageBox.Show("Error connecting to the server : " + e.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            InitializeComponent();
        }

        private void buttonInvokeRemoteObject_Click(object sender, EventArgs e)
        {
            if (remoteObject != null)
            {
                String result = remoteObject.SayHello(textBoxName.Text);
                   
                string[] split = result.Split(' ');
                foreach (string s in split) 
                {
                    currentID = s.ToString();
                }
                if (lastID == "")
                {
                    lastID = currentID;
                    instanceNumber++;
                }
                else
                {
                    if (lastID != currentID)
                    {
                        instanceNumber++;
                    }
                }

                MessageBox.Show("Result from remote object = " + result + " /// Nombre d'instance(s) d'objet(s) = " + instanceNumber, "Result", MessageBoxButtons.OK, MessageBoxIcon.Information);


                lastID = currentID;
            }
            else
            {
                MessageBox.Show("Error remote object not available", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
